//---------------------------------------------------------------------------- Package
const _ = require('lodash')
//---------------------------------------------------------------------------- Config
const { MYSQL } = require('../../config')
//---------------------------------------------------------------------------- Plugin
const mysql = require('../../plugin/util/mysql')
const sheet = require('../../plugin/util/sheet')
// ---------------------------------------------------------------------------- GET
exports.get = {
 /**
  * 直播列表(未开始、正在直播)
  */
  '/audio/list/manager': async (ctx, next) =>{
    let arg = []
    //预留帅选条件
    let where = ' where id >= 1'
    let limit = ' limit 0,10'
    if(ctx.query.name){
      where =  where + ' and name like "%'+ ctx.query.name +'%"'
    }
    if(ctx.query.page > 0){
      limit = ' limit ' + (ctx.query.page-1)*10 + ',10'
    }
    let sql = 'select * from audio' + where + ' order by time desc ' + limit
    let data = await mysql.query(MYSQL.XIONGAN, [sql], arg)
    sheet[0].data = data[0]
    ctx.body = sheet[0]
  },

  /**
   * 音频详情
   */
  '/audio/detail/manager/:id': async (ctx, next) =>{
    let id = ctx.params.id
    let data = await mysql.query(MYSQL.XIONGAN, ['select * from audio where id = ?'], [id])
    sheet[0].data = data[0]
    ctx.body = sheet[0]
  }


}
// ---------------------------------------------------------------------------- POST
exports.post = {
  /**
   * 添加音频
   */
  '/audio/add': async (ctx, next) => {
    let {name, img, url, time, intro} = ctx.request.fields
    time = Date.parse(new Date(time.replace(/\T/g,' '))).toString().slice(0,10)
    let data = await mysql.query(MYSQL.XIONGAN, ['insert into audio (name, img, url, time, intro) values(?,?,?,?,?)'], [name, img, url, time, intro])
    sheet[0].message = '添加成功'
    ctx.body = sheet[0]
  }

}
// ---------------------------------------------------------------------------- PUT
exports.put = {
  /**
   * 编辑音频
   */
  '/audio/edit/manager': async (ctx, next) => {
    let {name, img, url, time, intro, id} = ctx.request.fields
    time = Date.parse(new Date(time.replace(/\T/g,' '))).toString().slice(0,10)
    let data = await mysql.query(MYSQL.XIONGAN, [
      'update audio set name=?, img=?, url=?, time=?, intro=? where id=?'], 
      [name, img, url, time, intro, id]
    )
    sheet[0].data = data[0]
    ctx.body = sheet[0]
  }

}
// ---------------------------------------------------------------------------- DELETE
exports.delete = {
  /**
   * 删除音频
   */
  '/audio/delete/manager/:ids': async (ctx, next) =>{
    let ids = ctx.params.ids
    ids = ids.replace(/[|]/g, ',')
    let sql = ['delete from audio where id in (' + ids + ')']
    let arg = null
    await mysql.query(MYSQL.XIONGAN, sql, arg)
    sheet[0].message = '删除成功!'
    ctx.body = sheet[0]
  }
}